package afcp.alumni.action.page;

import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrorHandler;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import afcp.alumni.action.base.PageAction;
import afcp.alumni.model.SearchResult;
import afcp.alumni.model.db.Member;
import afcp.alumni.service.MemberService;
import afcp.alumni.service.SF;
import afcp.alumni.util.Conf;

/**
 * Action bean for the member page "/WEB-INF/jsp/membres.jsp".
 * 
 * @author Antoine
 * @see PageAction
 * 
 */
@UrlBinding(value=MembresAction.URL+"/{q}")// TODO revoir le formulaire pour qu'il renseigne correctement le paramètre q
//@Secure(roles="ADMIN")
public class MembresAction extends PageAction implements ValidationErrorHandler {
	
	private static final Log logger = LogFactory.getLog(MembresAction.class);

	public static final String URL = "/membres";
	@Override
	public String getUrl() {
		return URL;
	}
	
	// App-relative path to the default JSP file
	private static final String JSP = "/WEB-INF/jsp/membres.jsp";
	
	private static MemberService memberService = SF.member();
	
//	private int membersPerPage = Integer.parseInt(Conf.get("pagination.perpage"));

	@Override
	public String getTitle() {
		return msg("members.title");
	}

	@Override
	protected String defaultJsp() {
		return JSP;
	}

	@Override
	@Before
	protected void setPageVisitedBoolean() {
		setMembres();
	}

	@Override
	@DefaultHandler
	public Resolution view() {
//		queryMembers();
//		initPageCount();
		return this.toJsp();
	}
	
	// Partie recherche de membres

	@Validate(on="search", maxlength=255)
	private String q;
	
	public String getQ() {
		return q;
	}
	public void setQ(String q) {
		this.q = q;
	}
	
	// Fin partie recherche de membres
	
	// List of members paginated
	public static final String PAGE_PARAM = "p";

	private int p = 1;
	private int pp = Integer.parseInt(Conf.get("pagination.perpage"));
	// param pp (per page)
	public void setPp(int perPage) {
		pp = perPage;
	}
	
	// param p (page)
	public void setP(int page) {
		p = page;
	}

	private SearchResult<Member> members;
	
	private boolean queried = false;
	@Before(stages = LifecycleStage.CustomValidation)
	private void queryMembers() {
		if (!queried) {
			queried = true;
			
			if (q == null) {
				logger.info("search members with empty query. Returning a list with all members.");
				context.setQuery(null);
				members = memberService.getMembersOfPage(p, pp, context.getLocale());
			} else {
				logger.info("search members with query: " + q);
				context.setQuery(q);
				members = memberService.searchMembers(q, p, pp, context.getLocale());
				if (members != null && logger.isInfoEnabled()) {
					int size = members.getList().size();
					logger.info("Found " + size + " result" + (size > 1 ? "s" : "")
							+ " over " + members.getTotalResults()
							+ " total results.");
					for (Member member : members.getList()) {
						logger.info(member == null ? "null member" : ("Last name: "
								+ member.getLastName() + " ; first name: " + member
								.getFirstName()));
					}
				}
			}
			members.initPagination(getCurrentUrl(), PAGE_PARAM);
		}
	}
	
	public SearchResult<Member> getMembersFound() {
		return members;
	}
	
	// delegate methods
	@ValidationMethod
	public void checkPageValue(ValidationErrors errors) {
		members.checkPageValue(errors);
	}

//	public int getP() {
//		return members.getPage();
//	}
//	
//	public int getpMax() {
//		return members.getpMax();
//	}
//
//	public boolean getHasNextPage() {
//		return members.getHasNextPage();
//	}
//
//	public boolean getHasPreviousPage() {
//		return members.getHasPreviousPage();
//	}
//
//	public String getNextPageUrl() {
//		return members.getNextPageUrl();
//	}
//
//	public String getPreviousPageUrl() {
//		return members.getPreviousPageUrl();
//	}
	// end delegate methods
	// end list of members paginated

	@Override
	public Resolution handleValidationErrors(ValidationErrors errors)
			throws Exception {
		return this.toJsp();
	}
	
}
